package com.zbkj.service.service.adminregion.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.region.SearchRegionVo;
import com.zbkj.common.region.home.CitySaleRankResponse;
import com.zbkj.common.region.home.MerchantSaleRankResponse;
import com.zbkj.common.region.home.indicator.*;
import com.zbkj.service.dao.MerchantDao;
import com.zbkj.service.dao.OrderDao;
import com.zbkj.service.dao.ProductDao;
import com.zbkj.service.helper.region.RegionHelper;
import com.zbkj.service.service.adminregion.IRegionHomeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: IRegionHomeServiceImpl
 * @Description: TODO
 * @Author: fanbing
 * @Date: 2024/8/4 13:31
 * @Version: V1.0
 **/
@Service
@Slf4j
public class RegionHomeServiceImpl implements IRegionHomeService {


    @Autowired
    private RegionHelper regionHelper;

    @Autowired
    private MerchantDao merchantDao;

    @Resource
    private OrderDao orderDao;

    @Autowired
    private ProductDao productDao;

    @Override
    public RegionHomeIndicatorResponse getHomeIndicator() {
        SearchRegionVo currentUserRegion = regionHelper.getCurrentUserRegion();

        List<Integer> merchantIds = currentUserRegion.getMerchantIds();
        if (CollectionUtils.isEmpty(merchantIds)) {
            return new RegionHomeIndicatorResponse();
        }

        // 主页经商户数据指标响应对象
        RegionHomeMerchantIndicatorResponse merchantIndicator = this.getMerchantIndicator(currentUserRegion);

        // 销售额数据指标
        RegionHomeSalesIndicatorResponse salesIndicator = this.getSalesIndicator(currentUserRegion);

        // 订单数据指标
        RegionHomeOrderIndicatorResponse orderIndicator = this.getOrderIndicator(currentUserRegion);

        // 经营数据指标
        RegionHomeBusinessIndicatorResponse businessIndicator = this.getBusinessIndicator(currentUserRegion);

        return RegionHomeIndicatorResponse.builder()
                .merchantIndicator(merchantIndicator)
                .salesIndicator(salesIndicator)
                .orderIndicator(orderIndicator)
                .businessIndicator(businessIndicator)
                .build();
    }

    /**
     * 经营数据指标
     *
     * @param currentUserRegion
     * @return
     */
    private RegionHomeBusinessIndicatorResponse getBusinessIndicator(SearchRegionVo currentUserRegion) {
        RegionHomeBusinessIndicatorResponse indicatorResponse = new RegionHomeBusinessIndicatorResponse();
        List<Integer> merchantIds = currentUserRegion.getMerchantIds();
        //1、再售数量
        LambdaQueryWrapper<Product> qwTotal = new LambdaQueryWrapper<>();
        qwTotal.in(Product::getMerId, merchantIds);
        Integer saleCount = productDao.selectCount(qwTotal);
        indicatorResponse.setSaleCount(saleCount);

        //2、待审核数量
        LambdaQueryWrapper<Product> qwWaitAudit = new LambdaQueryWrapper<>();
        qwWaitAudit.in(Product::getMerId, merchantIds);
        // 审核状态：0-无需审核 1-待审核，2-审核成功，3-审核拒绝
        qwWaitAudit.eq(Product::getAuditStatus, 1);
        Integer waitAuditCount = productDao.selectCount(qwWaitAudit);
        indicatorResponse.setWaitAuditCount(waitAuditCount);

        //3、待核销数量
        LambdaQueryWrapper<Order> qwWaitVerification = new LambdaQueryWrapper<>();
        qwWaitVerification.in(Order::getMerId, merchantIds);
        //订单状态（0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消）
        qwWaitVerification.eq(Order::getStatus, 3);
        Integer waitVerificationCount = orderDao.selectCount(qwWaitVerification);
        indicatorResponse.setWaitVerificationCount(waitVerificationCount);

        //4、待退款数量
        LambdaQueryWrapper<Order> qwWaitRefund = new LambdaQueryWrapper<>();
        qwWaitRefund.in(Order::getMerId, merchantIds);
        //退款状态：0 未退款 1 申请中 2 部分退款 3 已退款
        qwWaitRefund.in(Order::getRefundStatus, Lists.newArrayList(1, 2, 3));
        Integer waitRefundCount = orderDao.selectCount(qwWaitRefund);
        indicatorResponse.setWaitRefundCount(waitRefundCount);

        //5、待发货数量
        LambdaQueryWrapper<Order> qwWaitDelivery = new LambdaQueryWrapper<>();
        qwWaitDelivery.in(Order::getMerId, merchantIds);
        //订单状态（0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消）
        qwWaitDelivery.in(Order::getStatus, Lists.newArrayList(1, 2));
        Integer waitDeliveryCount = orderDao.selectCount(qwWaitDelivery);
        indicatorResponse.setWaitRefundCount(waitDeliveryCount);

        return indicatorResponse;
    }

    /**
     * 主页经订单数据
     *
     * @param currentUserRegion
     * @return
     */
    private RegionHomeOrderIndicatorResponse getOrderIndicator(SearchRegionVo currentUserRegion) {
        RegionHomeOrderIndicatorResponse indicatorResponse = new RegionHomeOrderIndicatorResponse();
        List<Integer> merchantIds = currentUserRegion.getMerchantIds();
        // 1、总订单数
        LambdaQueryWrapper<Order> qwTotal = new LambdaQueryWrapper<>();
        qwTotal.in(Order::getMerId, merchantIds);
        Integer total = orderDao.selectCount(qwTotal);
        indicatorResponse.setTotalOrderCount(total);

        //2、今日订单数
        LambdaQueryWrapper<Order> qwToday = new LambdaQueryWrapper<>();
        qwToday.in(Order::getMerId, merchantIds);
        qwToday.between(Order::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()));
        Integer totalToday = orderDao.selectCount(qwToday);
        indicatorResponse.setTodayOrderCount(totalToday);


        //3、昨日订单数
        LambdaQueryWrapper<Order> qwYesterday = new LambdaQueryWrapper<>();
        qwYesterday.in(Order::getMerId, merchantIds);
        DateTime dateTime = DateUtil.offsetDay(new Date(), -1);
        qwYesterday.between(Order::getCreateTime, DateUtil.beginOfDay(dateTime), DateUtil.endOfDay(dateTime));
        Integer totalYesterday = orderDao.selectCount(qwYesterday);
        indicatorResponse.setYesterdayOrderCount(totalYesterday);

        return indicatorResponse;
    }

    /**
     * 主页经销售额数据指标
     *
     * @param currentUserRegion
     * @return
     */
    private RegionHomeSalesIndicatorResponse getSalesIndicator(SearchRegionVo currentUserRegion) {
        RegionHomeSalesIndicatorResponse indicatorResponse = new RegionHomeSalesIndicatorResponse();

        // 1、总销售额
        Map<String, Object> map = new HashMap<>();
        map.put("merchantIds", currentUserRegion.getMerchantIds());
        // 0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消
        map.put("statusList", Lists.newArrayList(1, 2, 3, 4, 5, 6));
        BigDecimal totalSales = orderDao.sumSales(map);
        indicatorResponse.setTotalSales(totalSales);

        //2、今日销售额
        Map<String, Object> mapToday = new HashMap<>();
        mapToday.put("merchantIds", currentUserRegion.getMerchantIds());
        // 0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消
        mapToday.put("statusList", Lists.newArrayList(1, 2, 3, 4, 5, 6));
        mapToday.put("startTime", DateUtil.beginOfDay(new Date()));
        mapToday.put("endTime", DateUtil.endOfDay(new Date()));
        BigDecimal todaySales = orderDao.sumSales(mapToday);
        indicatorResponse.setTodaySales(totalSales);


        //3、昨日销售额
        Map<String, Object> mapYesterday = new HashMap<>();
        mapYesterday.put("merchantIds", currentUserRegion.getMerchantIds());
        // 0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消
        mapYesterday.put("statusList", Lists.newArrayList(1, 2, 3, 4, 5, 6));
        DateTime dateTime = DateUtil.offsetDay(new Date(), -1);
        mapYesterday.put("startTime", DateUtil.beginOfDay(dateTime));
        mapYesterday.put("endTime", DateUtil.endOfDay(dateTime));
        BigDecimal salesYesterday = orderDao.sumSales(mapYesterday);
        indicatorResponse.setYesterdaySales(salesYesterday);

        return indicatorResponse;
    }

    /**
     * 商户数据指标
     *
     * @param currentUserRegion
     * @return
     */
    private RegionHomeMerchantIndicatorResponse getMerchantIndicator(SearchRegionVo currentUserRegion) {
        RegionHomeMerchantIndicatorResponse indicatorResponse = new RegionHomeMerchantIndicatorResponse();
        List<Integer> merchantIds = currentUserRegion.getMerchantIds();
        if (CollectionUtils.isEmpty(merchantIds)) {
            return indicatorResponse;
        }

        // 1、总商户数
        LambdaQueryWrapper<Merchant> qwTotal = new LambdaQueryWrapper<>();
        qwTotal.in(Merchant::getId, merchantIds);
        Integer count = merchantDao.selectCount(qwTotal);
        indicatorResponse.setTotalMerchantCount(count);

        // 2、今日新增商户数
        LambdaQueryWrapper<Merchant> qwToday = new LambdaQueryWrapper<>();
        qwToday.between(Merchant::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()));
        qwToday.in(Merchant::getId, merchantIds);
        Integer countToday = merchantDao.selectCount(qwToday);
        indicatorResponse.setTodayAddMerchantCount(countToday);

        // 3、昨日新增商户数
        LambdaQueryWrapper<Merchant> qwYesterday = new LambdaQueryWrapper<>();
        DateTime dateTime = DateUtil.offsetDay(new Date(), -1);
        qwYesterday.between(Merchant::getCreateTime, DateUtil.beginOfDay(dateTime), DateUtil.endOfDay(dateTime));
        qwYesterday.in(Merchant::getId, merchantIds);
        Integer countYesterday = merchantDao.selectCount(qwYesterday);
        indicatorResponse.setTodayAddMerchantCount(countYesterday);

        return indicatorResponse;
    }


    /**
     * 城市销售排行榜
     *
     * @return
     */
    @Override
    public List<CitySaleRankResponse> getCitySaleRank() {
        SearchRegionVo currentUserRegion = regionHelper.getCurrentUserRegion();

        Map<String, Object> map = new HashMap<>();
        map.put("size", 5);
        map.put("merchantIds", currentUserRegion.getMerchantIds());
        // 0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消
        map.put("statusList", Lists.newArrayList(1, 2, 3, 4, 5, 6));
        List<CitySaleRankResponse> rankResponses = orderDao.getCitySaleRank(map);

        return rankResponses;
    }


    /**
     * 商户销售排行榜
     *
     * @return
     */
    @Override
    public List<MerchantSaleRankResponse> getMerchantSaleRank() {
        SearchRegionVo currentUserRegion = regionHelper.getCurrentUserRegion();

        Map<String, Object> map = new HashMap<>();
        map.put("size", 5);
        map.put("merchantIds", currentUserRegion.getMerchantIds());
        // 0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消
        map.put("statusList", Lists.newArrayList(1, 2, 3, 4, 5, 6));
        List<MerchantSaleRankResponse> rankResponses = orderDao.getMerchantSaleRank(map);

        return rankResponses;
    }
}
